package com.xiaoyu.tool.service.order;

import com.xiaoyu.tool.entity.order.LineItem;
import com.xiaoyu.tool.entity.order.Order;
import com.xiaoyu.tool.entity.product.Product;
import com.xiaoyu.tool.repository.order.LineItemRepository;
import com.xiaoyu.tool.repository.product.ProductFormatRepository;
import com.xiaoyu.tool.repository.product.ProductRepository;
import com.xiaoyu.tool.response.order.OrderLineItemRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoyu on 2018/08/14
 */
@Service
public class LineItemService {

    @Autowired
    private LineItemRepository lineItemRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductFormatRepository productFormatRepository;

     
    public LineItem getOne(Long lineItemId) {
        return lineItemRepository.findById(lineItemId).orElse(null);
    }


     
    public boolean handleProductInventory(List<LineItem> items) {
        for (LineItem lineItem : items) {
            Long productId = lineItem.getProductId();
            Product product = productRepository.findById(productId).orElse(null);
            if (product.getInventory() - lineItem.getQuantity() < 0) {
                return true;
            }
            product.setInventory(product.getInventory() - lineItem.getQuantity());
            productRepository.save(product);
        }
        return false;
    }

     
    public List<LineItem> transformFromModel(List<OrderLineItemRequest> items, Order order) {
        List<LineItem> lineItems = new ArrayList<>();
        for (OrderLineItemRequest orderLineItem : items) {
            LineItem item = lineItemRepository.findById(orderLineItem.getProductId()).orElse(null);
            item.setCartId(null);
            item.setOrderId(order.getId());
            item.setPrice(productFormatRepository.findById(item.getFormatId()).orElse(null).getSellPrice());
            LineItem lineItem = lineItemRepository.save(item);
            lineItems.add(lineItem);
        }
        return lineItems;
    }


}










